package com.itheima.web.controller.store;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.utils.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;


@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");
        if ("list".equals(operation)) {
            findAll(req, resp);
        } else if ("toAdd".equals(operation)) {
            toAdd(req, resp);
        } else if ("save".equals(operation)) {
            try {
                save(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("delete".equals(operation)) {
            delete(req, resp);
        } else if ("toEdit".equals(operation)) {
            toEdit(req, resp);
        } else if ("edit".equals(operation)) {
            try {
                update(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("toTestUpload".equals(operation)) {
            toTestUpload(req, resp);
        } else if ("testFileUpload".equals(operation)) {
            try {
                testFileUpload(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("toExport".equals(operation)) {
            toExport(req, resp);
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNum = 1;
        int pageSize = 5;
        if (StringUtils.isNoneBlank(req.getParameter("page"))) {
            pageNum = Integer.parseInt(req.getParameter("page"));
        }
        if (StringUtils.isNoneBlank(req.getParameter("size"))) {
            pageSize = Integer.parseInt(req.getParameter("size"));
        }
        PageInfo all = questionService.findAll(pageNum, pageSize);
        req.setAttribute("page", all);

        req.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(req, resp);

    }


    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        List<FileItem> fileItems = fileUpload.parseRequest(req);
        boolean flag = false; //是否携带文件 标记
        boolean check = false;//图片格式是否满足要求 标记
        String name=null;
        for (FileItem file : fileItems) {
             name = file.getName();
            if (StringUtils.isNoneBlank(name)) {
                flag=true;
                if(!checkImg(name)){
                    resp.getWriter().write("图片格式不正确!");
                    return;
                }
                break;
            }
        }
        Question question = BeanUtil.fillBean(fileItems, Question.class);
        String picture = questionService.save(question, flag);

        for (FileItem item : fileItems) {
            if (flag && !item.isFormField()) {
                item.write(new File(req.getServletContext().getRealPath("upload"), picture + ".jpg"));
            }
        }
        resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");

    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Company> allCompanys = companyService.findAll();
        List<Catalog> allCatalogs = catalogService.findAll();
        req.setAttribute("companyList", allCompanys);
        req.setAttribute("catalogList", allCatalogs);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(req, resp);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] id = req.getParameter("id").split(",");
        questionService.delete(id);
        resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");

    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Question question = questionService.findById(id);
        req.setAttribute("question", question);
        List<Company> allCompanys = companyService.findAll();
        List<Catalog> allCatalogs = catalogService.findAll();
        req.setAttribute("companyList", allCompanys);
        req.setAttribute("catalogList", allCatalogs);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(req, resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        List<FileItem> fileItems = fileUpload.parseRequest(req);
        boolean flag = false;

        for (FileItem fileItem : fileItems) {
            String name = fileItem.getName();
            if (StringUtils.isNoneBlank(fileItem.getName())) {
                flag = true;
//                if(name.endsWith("jpg")||name.endsWith("png")){
                break;
//                }
            }
//            resp.getWriter().write("<script>alert('图片上传失败,仅仅支持 jpg , png 格式!')</script>");
//            findAll(req,resp);
//            req.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(req, resp);
//            return;
        }
        Question question = BeanUtil.fillBean(fileItems, Question.class);
        questionService.update(question, flag);
        for (FileItem item : fileItems) {
            if (flag && !item.isFormField()) {
                item.write(new File(req.getServletContext().getRealPath("upload"), question.getId() + ".jpg"));
            }
        }
        resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");
    }

    private void toTestUpload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println(this);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/testUpload.jsp").forward(req, resp);

    }


    private void toExport(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        String fileName = new String("面试题集.xlsx".getBytes(), "ISO8859-1");

        resp.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

        ServletOutputStream outputStream = resp.getOutputStream();
        ByteArrayOutputStream report = questionService.getReport();
        report.writeTo(outputStream);
        outputStream.flush();
        report.close();


    }


    private void testFileUpload(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /**
     * 上传问题的图片格式校验判断
     */
    private boolean checkImg(String imgName) {
        int i = imgName.lastIndexOf(".");
        if(i==0){
            return false;
        }else{
            return super.imgList.contains(imgName.substring(i+1));
        }
    }


}
